package com.ushine.web.config.database;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @Author: yangls
 * @Date: 2021/4/21 15:16
 * @Description: mybatis plus 日志数据源配置
 * @Version 1.0
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"com.ushine.web.log.mapper"}, sqlSessionFactoryRef = "mybatisLogSqlSessionFactory")
public class MybatisLogShardDruidConfig {

    @Resource
    @Qualifier("shardingSphereDataSource")
    DataSource shardingSphereDataSource;

    @Resource
    @Qualifier("permitPaginationInnerInterceptor")
    PaginationInnerInterceptor paginationInnerInterceptor;

    @Resource
    @Qualifier("permitGlobalConfig")
    GlobalConfig globalConfig;

    @Bean(name = "mybatisLogSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(shardingSphereDataSource);
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 添加防止全表更新与删除插件
        BlockAttackInnerInterceptor blockAttackInnerInterceptor = new BlockAttackInnerInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(blockAttackInnerInterceptor);
        // 添加分页插件
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        sqlSessionFactoryBean.setPlugins(mybatisPlusInterceptor);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("mybatisLogTransactionManager")
    public DataSourceTransactionManager primaryDataSourceTransactionManager(@Qualifier("shardingSphereDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("mybatisLogSqlSessionTemplate")
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("mybatisLogSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
